package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.Intent;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.CityHistoryAdapter;
import com.wuliupai.delivery.wuliupaidelivery.db.CityHistoryBean;
import com.wuliupai.delivery.wuliupaidelivery.db.DBHelper;
import com.wuliupai.delivery.wuliupaidelivery.db.DBUtil;
import com.wuliupai.delivery.wuliupaidelivery.db.ReadAssets;
import com.wuliupai.delivery.wuliupaidelivery.utils.LocationUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;

import java.util.List;

/**
 * Descriptions：地址选择的第一步
 * <p>
 * Author：ChenME
 * Date：2017/1/5
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_place_select_step1)
public class PlaceSelectActivityStep1 extends AppBaseActivity {

    @Bean(DBUtil.class)
    DBUtil dbUtil;

    @ViewById(R.id.tv_currentLocation)
    TextView tv_currentLocation;//当前定位

    @ViewById(R.id.tv_historyLabel)
    TextView tv_historyLabel;
    @ViewById(R.id.gridView)
    GridView gridView;

    private List<CityHistoryBean> historyList;
    private CityHistoryAdapter adapter;

    public static final int Result_CompleteAddress = 0xff21;
    private static final int Request_CompleteAddress = 0xff20;

    private DBHelper dbHelper;

    private String[] resultProvince = new String[2];
    private String[] resultCity = new String[2];
    private String[] resultArea = new String[2];

    private LocationClient mLocationClient;//定位SDK的核心类

    private boolean localSuccessful = false;//定位是成功

    private ReadAssets readAssets;

    @AfterViews
    void onPageStart() {
        setDefaultTitle(this, "所在区域");
        readAssets = new ReadAssets();
        dbHelper = new DBHelper(this);

        //开启定位
        startLocation();
        setHistoryView();
    }

    private void setHistoryView() {
        historyList = dbHelper.getTopHistoryData(6);
        if (historyList.size() > 0) {

            tv_historyLabel.setVisibility(View.VISIBLE);
            gridView.setVisibility(View.VISIBLE);
            adapter = new CityHistoryAdapter(this, historyList);
            gridView.setAdapter(adapter);

            gridView.setOnItemClickListener((parent, view, position, id) -> {
                CityHistoryBean bean = historyList.get(position);
                resultProvince[0] = bean.getProvinceCode();
                resultProvince[1] = bean.getProvince();
                resultCity[0] = bean.getCityCode();
                resultCity[1] = bean.getCity();
                resultArea[0] = bean.getAreaCode();
                resultArea[1] = bean.getArea();
                setResultAndFinishPage();
            });
        }
    }

    /**
     * 开启定位
     */
    private void startLocation() {
        tv_currentLocation.setText(getString(R.string.string_selectPlace_localingTips));
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(new MyLocationListener());    //注册监听函数
        LocationUtil.initLocationClient(mLocationClient);
        mLocationClient.start();
    }

    /**
     * 设置选择结果并关闭页面
     */
    private void setResultAndFinishPage() {
        dbHelper.insertCityHistory(new CityHistoryBean(resultArea[0], resultCity[0], resultProvince[0],
                resultArea[1], resultCity[1], resultProvince[1]));
        Intent intent = new Intent();
        intent.putExtra("province", resultProvince);
        intent.putExtra("city", resultCity);
        intent.putExtra("area", resultArea);
        setResult(Result_CompleteAddress, intent);
        onBackPressed();
    }


    /**
     * 手动搜索点击事件
     */
    @Click(R.id.tv_keyInput)
    void onKeyInputClick() {
        PlaceSearchActivity_.intent(this).startForResult(Request_CompleteAddress);
        animUtils.leftInAnimation(this);
    }

    /**
     * 当前定位的点击事件
     */
    @Click(R.id.ll_currentLocation)
    void onCurrentLocationClick() {
        if (localSuccessful) {
            resultProvince[0] = dbUtil.findProvinceByProvinceName(readAssets.openDatabase(this), resultProvince[1]).get(0).getCode();
            resultCity[0] = dbUtil.findCityByCityName(readAssets.openDatabase(this), resultCity[1]).get(0).getCode();
            resultArea[0] = dbUtil.findAreaByAreaName(readAssets.openDatabase(this), resultArea[1]).get(0).getCode();
            setResultAndFinishPage();
        } else {
            tv_currentLocation.setText(getString(R.string.string_selectPlace_localingTips));
            mLocationClient.start();
        }
    }

    /**
     * 手动选择
     */
    @Click(R.id.tv_placeSelect)
    void onPlaceSelectClick() {
        PlaceSelectActivityStep2_.intent(this).startForResult(Request_CompleteAddress);
        animUtils.leftInAnimation(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.leftOutAnimation(this);
    }

    /**
     * 手动输入、手动选择地址结果返回
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Request_CompleteAddress)
    void onSelectPlaceByInputResult(int resultCode, Intent data) {
        if (PlaceSearchActivity.Result_PlaceSearch == resultCode ||
                PlaceSelectActivityStep2.Result_SelectPlace == resultCode) {
            resultArea = data.getStringArrayExtra("area");
            resultCity = data.getStringArrayExtra("city");
            resultProvince = data.getStringArrayExtra("province");
            setResultAndFinishPage();
        }
    }

    /**
     * 百度地图定位的监听器
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            mLocationClient.stop();
            Address address = location.getAddress();
            String city = address.city;
            String district = address.district;
            if (null != city && null != district) {
                localSuccessful = true;
                resultProvince[1] = address.province;
                resultCity[1] = city;
                resultArea[1] = district;
                tv_currentLocation.setText(city + " - " + district);
            } else {
                localSuccessful = false;
                tv_currentLocation.setText(getString(R.string.string_selectPlace_localFailTips));
            }
        }
    }
}